package cn.edu.zzuli.nothinglink.handler;

import cn.edu.zzuli.nothinglink.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class CurrentUserInterceptor implements HandlerInterceptor {

    //在一个线程内可以共享的数据。
    public static ThreadLocal<Integer> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("nothing-token");

        //这里不需要校验，毕竟鉴权已经交给shiro了
        if (token == null) {
            return true;
        }

        Boolean verify = TokenUtil.verify(token);
        if (verify) {
            String uId = TokenUtil.getAccount(token);

            //我们把 uId放入到 threadLocal 达到共享的目的
            threadLocal.set(Integer.valueOf(uId));
            return true;
        }

        //其实这里不用返回 false。校验失败会报错，然后被全局异常捕捉直接返回 json。
        return false;

    }
}

